package com.selune.online.ordering.system.common.util;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.selune.online.ordering.system.common.properties.QiniuProperties;
import java.io.File;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 *
 * @author xiaoyp
 * @date 2020/4/1
 * <p>
 * Description:
 */
@Slf4j
@Component
public class QiniuUploadUtils {
	
	@Autowired
	private QiniuProperties qiniuProperties;
	
	/**
	 * 将图片上传到七牛云
	 *
	 * @param file 文件
	 * @param key  保存在空间中的名字，如果为空会使用文件的hash值为文件名
	 * @return 返回地址
	 */
	public String uploadFile(File file, String key) {
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.autoZone());
		UploadManager uploadManager = new UploadManager(cfg);
		// 配置
		String accessKey = qiniuProperties.getAccessKey();
		String secretKey = qiniuProperties.getSecretKey();
		String bucket = qiniuProperties.getBucketName();
		String path = qiniuProperties.getPath();
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		try {
			Auth auth = Auth.create(accessKey, secretKey);
			String upToken = auth.uploadToken(bucket);
			try {
				Response response = uploadManager.put(file, key, upToken);
				// 解析上传成功的结果
				DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
				String returnPath = path + "/" + putRet.key;
				log.info("保存地址: {}", returnPath);
				return returnPath;
			} catch (QiniuException ex) {
				Response r = ex.response;
				System.err.println(r.toString());
				try {
					System.err.println(r.bodyString());
				} catch (QiniuException ex2) {
					// ignore
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}

